package cn.coderwe.service;

import cn.coderwe.model.MultiLevelBook;
import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.mozilla.universalchardet.UniversalDetector;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : coderwe
 */
public class BookReader {
    private final static String CHAPTER_REGULARIZATION = "^(第[零一二三四五六七八九十百千0-9]+章)[ ：]|(番外) |^(第[零一二三四五六七八九十百千0-9]+章)|^(第\\d+章|免费番外\\d+|.+番外：.+).*";
    private final static Pattern PATTERN = Pattern.compile(CHAPTER_REGULARIZATION);
    private final static Pattern SUBSECTION_PATTERN = Pattern.compile("^第[一二三四五六七八九十百千0-9]+卷");
    private final static Pattern WRITER_PATTERN = Pattern.compile("(?<=作者[：:]).*");
    private final static Pattern INTRO_PATTERN = Pattern.compile("^(内容|作品)?简介[：:]$");

    private boolean isIntro = false;

    /**
     * 读取多级书目文件并返回一个MultiLevelBook对象
     *
     * @param filePath 文件路径
     * @return 读取成功的MultiLevelBook对象
     */
    public MultiLevelBook read(String filePath) throws IOException {
        MultiLevelBook multiLevelBook = new MultiLevelBook(FileUtil.getPrefix(filePath));
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String encoding = detectEncoding(fileContent);
        System.out.println(encoding);
        try (InputStream inputStream = Files.newInputStream(Paths.get(filePath));
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encoding);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                Matcher writerMatcher = WRITER_PATTERN.matcher(line);
                if (multiLevelBook.getBookWriter() == null && writerMatcher.find()) {
                    String writer = writerMatcher.group();
                    multiLevelBook.setBookWriter(writer);
                }
                if (INTRO_PATTERN.matcher(line).find()) {
                    isIntro = true;
                    continue;
                }
                if (SUBSECTION_PATTERN.matcher(line).find()) { // 如果是子目录一级的行
                    isIntro = false;
                    multiLevelBook.setLevel1Dir(line); // 将子目录一级路径添加到MultiLevelBook对象中
                    continue;
                }
                Matcher matcher = PATTERN.matcher(line);
                if (matcher.find()) { // 如果是子目录二级的行
                    isIntro = false;
                    String group = matcher.group();
                    StringBuffer sb = new StringBuffer();
                    matcher.appendReplacement(sb, group + " ");
                    matcher.appendTail(sb);
                    multiLevelBook.setLevel2Dir(sb.toString()); // 将子目录二级路径添加到MultiLevelBook对象中
                } else {
                    if (StringUtils.isNotBlank(line) && isIntro) { // 排除空行
                        multiLevelBook.addIntro(line); // 将内容添加到MultiLevelBook对象中
                    }
                    // 如果是普通内容行
                    if (StringUtils.isNotBlank(line) && !isIntro) { // 排除空行
                        multiLevelBook.addContent("　　" + line.replaceAll("^[\\s\\u3000]+|[\\s\\u3000]+$", "")); // 将内容添加到MultiLevelBook对象中
                    }
                }
            }
            multiLevelBook.addOver(); // 添加结束标记到MultiLevelBook对象中
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
        return multiLevelBook; // 返回读取成功的MultiLevelBook对象
    }
    public static String detectEncoding(byte[] content) {
        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(content, 0, content.length);
        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        return encoding;
    }
}
